package com.md.mod.core;

import com.md.mod.utils.JSONResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * ********************************
 *
 * @author zhaoqingwei.
 * 天下英雄出我辈，一入江湖岁月催.
 * 20192019/1/2915:45
 * ********************************
 * 描述：
 * <p>
 * 注释：
 **/
@ControllerAdvice
public class CommonExceptionHandler {
    private Logger log = LoggerFactory.getLogger(CommonExceptionHandler.class);
    private static final String COMM_ERROR_VIEW = "/error";

    @ExceptionHandler(value = Exception.class)
    public Object myExceptionHandler(HttpServletRequest req, HttpServletRequest rep, Exception e){

        log.error("进全局捕获异常类！");

        if (isAjax(req)){
            return JSONResult.commonAjaxException(e);
        }else {
            ModelAndView mav = new ModelAndView();
            mav.addObject("e", e.getMessage());
            mav.addObject("url", req.getRequestURL());
            mav.addObject("msg", "服务器有点类,请联系管理员处理!");
            mav.setViewName(COMM_ERROR_VIEW);
            return mav;
        }
    }

    public static boolean isAjax(HttpServletRequest httpRequest){
        return  (httpRequest.getHeader("X-Requested-With") != null && "XMLHttpRequest" .equals( httpRequest.getHeader("X-Requested-With").toString()) );
    }
}
